﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Epam.PhotoGallery.Interfaces.DataTransferObjects;
using System.Reflection;

namespace Epam.PhotoGallery.Site.CustomModelBinders
{
    public class CommentModelBinder : DefaultModelBinder
    {
        private const string IMAGES_COLLECTION_NAME = "Images";
        private const string IMAGES_URL_COLLECTION_NAME = "ImagesUrl";

        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var resultObj = base.BindModel(controllerContext, bindingContext);

            FillImages(resultObj, controllerContext, bindingContext);

            return resultObj;
        }

        private void FillImages(object resultObj, ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(IMAGES_COLLECTION_NAME);
            List<CommunityImage> images = new List<CommunityImage>();

            if (valueResult != null)
            {
                HttpPostedFileBase[] files = valueResult.ConvertTo(typeof(HttpPostedFileBase[])) as HttpPostedFileBase[];


                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null)
                        {
                            CommunityImage image = new CommunityImage(ImageStorageType.Database);
                            byte[] imageContent = new byte[file.ContentLength];

                            file.InputStream.Read(imageContent, 0, file.ContentLength - 1);
                            image.ImageData.Content = imageContent;
                            image.ImageData.MimeType = file.ContentType;

                            images.Add(image);
                        }
                    }
                }
            }

            valueResult = bindingContext.ValueProvider.GetValue(IMAGES_URL_COLLECTION_NAME);

            if (valueResult != null)
            {
                IEnumerable<string> filesUrl = valueResult.ConvertTo(typeof(IEnumerable<string>)) as IEnumerable<string>;

                if (filesUrl != null)
                {
                    foreach (var url in filesUrl)
                    {
                        CommunityImage image = new CommunityImage(ImageStorageType.Url);
                        image.Path = url;

                        images.Add(image);
                    }
                }
            }

            PropertyInfo imageProperty = bindingContext.ModelType.GetProperty(IMAGES_COLLECTION_NAME);

            imageProperty.SetValue(resultObj, images, null);
        }
    }
}